<template>
  <div class="rich-text-editor">
    <div class="editor-toolbar" v-if="!readonly">
      <!-- 工具栏 -->
      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="formatText('bold')" :class="{ active: formats.bold }" title="粗体 (Ctrl+B)">
            <el-icon><strong>B</strong></el-icon>
          </el-button>
          <el-button @click="formatText('italic')" :class="{ active: formats.italic }" title="斜体 (Ctrl+I)">
            <el-icon><em>I</em></el-icon>
          </el-button>
          <el-button @click="formatText('underline')" :class="{ active: formats.underline }" title="下划线 (Ctrl+U)">
            <el-icon><u>U</u></el-icon>
          </el-button>
          <el-button @click="formatText('strike')" :class="{ active: formats.strike }" title="删除线">
            <el-icon><s>S</s></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-select v-model="currentHeader" @change="formatHeader" size="small" style="width: 120px;" placeholder="标题">
          <el-option label="正文" :value="false" />
          <el-option label="标题 1" :value="1" />
          <el-option label="标题 2" :value="2" />
          <el-option label="标题 3" :value="3" />
          <el-option label="标题 4" :value="4" />
          <el-option label="标题 5" :value="5" />
          <el-option label="标题 6" :value="6" />
        </el-select>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="formatText('list', 'ordered')" title="有序列表">
            <el-icon><List /></el-icon>
          </el-button>
          <el-button @click="formatText('list', 'bullet')" title="无序列表">
            <el-icon><Operation /></el-icon>
          </el-button>
          <el-button @click="formatText('indent', '+1')" title="增加缩进">
            <el-icon><Right /></el-icon>
          </el-button>
          <el-button @click="formatText('indent', '-1')" title="减少缩进">
            <el-icon><Back /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="formatText('align', 'left')" title="左对齐">
            <el-icon><AlignLeft /></el-icon>
          </el-button>
          <el-button @click="formatText('align', 'center')" title="居中对齐">
            <el-icon><AlignCenter /></el-icon>
          </el-button>
          <el-button @click="formatText('align', 'right')" title="右对齐">
            <el-icon><AlignRight /></el-icon>
          </el-button>
          <el-button @click="formatText('align', 'justify')" title="两端对齐">
            <el-icon><AlignJustify /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="insertLink" title="插入链接">
            <el-icon><Link /></el-icon>
          </el-button>
          <el-button @click="insertImage" title="插入图片">
            <el-icon><Picture /></el-icon>
          </el-button>
          <el-button @click="insertVideo" title="插入视频">
            <el-icon><VideoPlay /></el-icon>
          </el-button>
          <el-button @click="insertTable" title="插入表格">
            <el-icon><Grid /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="insertCodeBlock" title="代码块">
            <el-icon><Document /></el-icon>
          </el-button>
          <el-button @click="insertFormula" title="数学公式">
            <el-icon><Calculator /></el-icon>
          </el-button>
          <el-button @click="insertDivider" title="分割线">
            <el-icon><Minus /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-color-picker v-model="textColor" @change="changeTextColor" size="small" />
        <el-color-picker v-model="backgroundColor" @change="changeBackgroundColor" size="small" />
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="undo" :disabled="!canUndo" title="撤销 (Ctrl+Z)">
            <el-icon><RefreshLeft /></el-icon>
          </el-button>
          <el-button @click="redo" :disabled="!canRedo" title="重做 (Ctrl+Y)">
            <el-icon><RefreshRight /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button @click="toggleFullscreen" size="small" title="全屏编辑">
          <el-icon><FullScreen /></el-icon>
        </el-button>
        <el-button @click="togglePreview" size="small" title="预览">
          <el-icon><View /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 编辑器容器 -->
    <div class="editor-container" :class="{ fullscreen: isFullscreen, readonly: readonly }">
      <div
        ref="editorRef"
        class="editor-content"
        contenteditable="true"
        :data-placeholder="placeholder"
        @input="handleInput"
        @focus="handleFocus"
        @blur="handleBlur"
        @paste="handlePaste"
        v-html="content"
      ></div>

      <!-- 预览模式 -->
      <div v-if="showPreview" class="editor-preview">
        <div class="preview-content" v-html="previewContent"></div>
      </div>
    </div>

    <!-- 字数统计 -->
    <div class="editor-footer" v-if="showWordCount">
      <div class="word-count">
        <span>字符数: {{ wordCount.characters }}</span>
        <span>单词数: {{ wordCount.words }}</span>
        <span>段落数: {{ wordCount.paragraphs }}</span>
      </div>
    </div>

    <!-- 链接插入对话框 -->
    <el-dialog v-model="linkDialogVisible" title="插入链接" width="500px">
      <el-form :model="linkForm" label-width="80px">
        <el-form-item label="链接文本">
          <el-input v-model="linkForm.text" placeholder="请输入链接文本" />
        </el-form-item>
        <el-form-item label="链接地址">
          <el-input v-model="linkForm.url" placeholder="请输入链接地址" />
        </el-form-item>
        <el-form-item label="打开方式">
          <el-radio-group v-model="linkForm.target">
            <el-radio label="_self">当前窗口</el-radio>
            <el-radio label="_blank">新窗口</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="linkDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInsertLink">确定</el-button>
      </template>
    </el-dialog>

    <!-- 图片上传对话框 -->
    <el-dialog v-model="imageDialogVisible" title="插入图片" width="600px">
      <el-tabs v-model="imageTabActive">
        <el-tab-pane label="上传图片" name="upload">
          <el-upload
            ref="uploadRef"
            class="image-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :on-success="handleImageUploadSuccess"
            :on-error="handleImageUploadError"
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将图片拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 jpg/png/gif 文件，且不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="网络图片" name="url">
          <el-form :model="imageForm" label-width="80px">
            <el-form-item label="图片地址">
              <el-input v-model="imageForm.url" placeholder="请输入图片地址" />
            </el-form-item>
            <el-form-item label="替代文本">
              <el-input v-model="imageForm.alt" placeholder="请输入图片描述" />
            </el-form-item>
            <el-form-item label="图片标题">
              <el-input v-model="imageForm.title" placeholder="请输入图片标题" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="imageDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInsertImage">确定</el-button>
      </template>
    </el-dialog>

    <!-- 表格插入对话框 -->
    <el-dialog v-model="tableDialogVisible" title="插入表格" width="400px">
      <el-form :model="tableForm" label-width="80px">
        <el-form-item label="行数">
          <el-input-number v-model="tableForm.rows" :min="1" :max="20" />
        </el-form-item>
        <el-form-item label="列数">
          <el-input-number v-model="tableForm.cols" :min="1" :max="10" />
        </el-form-item>
        <el-form-item label="表格样式">
          <el-select v-model="tableForm.style" style="width: 100%">
            <el-option label="默认" value="default" />
            <el-option label="带边框" value="bordered" />
            <el-option label="斑马纹" value="striped" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="tableDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInsertTable">确定</el-button>
      </template>
    </el-dialog>

    <!-- 代码块插入对话框 -->
    <el-dialog v-model="codeDialogVisible" title="插入代码块" width="600px">
      <el-form :model="codeForm" label-width="80px">
        <el-form-item label="编程语言">
          <el-select v-model="codeForm.language" style="width: 100%" filterable>
            <el-option v-for="lang in codeLanguages" :key="lang.value" :label="lang.label" :value="lang.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="代码内容">
          <el-input
            v-model="codeForm.code"
            type="textarea"
            :rows="10"
            placeholder="请输入代码内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="codeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInsertCode">确定</el-button>
      </template>
    </el-dialog>

    <!-- 数学公式插入对话框 -->
    <el-dialog v-model="formulaDialogVisible" title="插入数学公式" width="600px">
      <el-form :model="formulaForm" label-width="80px">
        <el-form-item label="公式类型">
          <el-radio-group v-model="formulaForm.type">
            <el-radio label="inline">行内公式</el-radio>
            <el-radio label="block">块级公式</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="LaTeX公式">
          <el-input
            v-model="formulaForm.latex"
            type="textarea"
            :rows="5"
            placeholder="请输入LaTeX公式，如：E = mc^2"
            @input="updateFormulaPreview"
          />
        </el-form-item>
        <el-form-item label="预览">
          <div class="formula-preview" ref="formulaPreviewRef"></div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formulaDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInsertFormula">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, watch, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// Props定义
interface Props {
  modelValue?: string
  placeholder?: string
  readonly?: boolean
  height?: string | number
  showWordCount?: boolean
  uploadUrl?: string
  uploadHeaders?: Record<string, string>
  maxLength?: number
  theme?: 'snow' | 'bubble'
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: '请输入内容...',
  readonly: false,
  height: '400px',
  showWordCount: true,
  uploadUrl: '/api/upload/image',
  uploadHeaders: () => ({}),
  maxLength: 0,
  theme: 'snow'
})

// Emits定义
interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'change', value: string): void
  (e: 'focus'): void
  (e: 'blur'): void
  (e: 'ready'): void
}

const emit = defineEmits<Emits>()

// 响应式数据
const editorRef = ref<HTMLElement>()
const uploadRef = ref()
const formulaPreviewRef = ref<HTMLElement>()
const content = ref(props.modelValue)

// 编辑器状态
const isFullscreen = ref(false)
const showPreview = ref(false)
const canUndo = ref(false)
const canRedo = ref(false)

// 格式状态
const formats = reactive({
  bold: false,
  italic: false,
  underline: false,
  strike: false
})

const currentHeader = ref<number | false>(false)
const textColor = ref('#000000')
const backgroundColor = ref('#ffffff')

// 对话框状态
const linkDialogVisible = ref(false)
const imageDialogVisible = ref(false)
const tableDialogVisible = ref(false)
const codeDialogVisible = ref(false)
const formulaDialogVisible = ref(false)

// 表单数据
const linkForm = reactive({
  text: '',
  url: '',
  target: '_self'
})

const imageForm = reactive({
  url: '',
  alt: '',
  title: ''
})

const imageTabActive = ref('upload')

const tableForm = reactive({
  rows: 3,
  cols: 3,
  style: 'default'
})

const codeForm = reactive({
  language: 'javascript',
  code: ''
})

const formulaForm = reactive({
  type: 'inline',
  latex: ''
})

// 代码语言选项
const codeLanguages = [
  { label: 'JavaScript', value: 'javascript' },
  { label: 'TypeScript', value: 'typescript' },
  { label: 'HTML', value: 'html' },
  { label: 'CSS', value: 'css' },
  { label: 'Python', value: 'python' },
  { label: 'Java', value: 'java' },
  { label: 'C++', value: 'cpp' },
  { label: 'C#', value: 'csharp' },
  { label: 'PHP', value: 'php' },
  { label: 'Go', value: 'go' },
  { label: 'Rust', value: 'rust' },
  { label: 'SQL', value: 'sql' },
  { label: 'Shell', value: 'bash' },
  { label: 'JSON', value: 'json' },
  { label: 'XML', value: 'xml' },
  { label: 'Markdown', value: 'markdown' }
]

// 计算属性
const previewContent = computed(() => {
  return content.value || ''
})

const wordCount = computed(() => {
  const text = editorRef.value?.textContent || ''
  return {
    characters: text.length,
    words: text.trim() ? text.trim().split(/\s+/).length : 0,
    paragraphs: text.trim() ? text.split(/\n\s*\n/).length : 0
  }
})

// 处理输入
const handleInput = (event: Event) => {
  const target = event.target as HTMLElement
  content.value = target.innerHTML
  emit('update:modelValue', content.value)
  emit('change', content.value)
}

// 处理焦点
const handleFocus = () => {
  emit('focus')
}

// 处理失焦
const handleBlur = () => {
  emit('blur')
}

// 处理粘贴
const handlePaste = (event: ClipboardEvent) => {
  event.preventDefault()
  const text = event.clipboardData?.getData('text/plain') || ''
  document.execCommand('insertText', false, text)
}

// 初始化编辑器
const initEditor = async () => {
  if (!editorRef.value) return

  try {
    // 设置初始内容
    if (props.modelValue) {
      content.value = props.modelValue
      editorRef.value.innerHTML = props.modelValue
    }

    // 设置编辑器高度
    if (typeof props.height === 'number') {
      editorRef.value.style.height = `${props.height}px`
    } else {
      editorRef.value.style.height = props.height
    }

    // 设置只读模式
    if (props.readonly) {
      editorRef.value.contentEditable = 'false'
    }

    emit('ready')
  } catch (error) {
    console.error('编辑器初始化失败:', error)
    ElMessage.error('编辑器初始化失败')
  }
}

// 设置键盘快捷键
const setupKeyboardShortcuts = () => {
  // 简化实现，不需要复杂的快捷键
}

// 更新格式状态
const updateFormatStates = () => {
  // 简化实现
  formats.bold = document.queryCommandState('bold')
  formats.italic = document.queryCommandState('italic')
  formats.underline = document.queryCommandState('underline')
  formats.strike = document.queryCommandState('strikeThrough')
}

// 更新撤销重做状态
const updateUndoRedoStates = () => {
  // 简化实现
  canUndo.value = true
  canRedo.value = true
}

// 格式化文本
const formatText = (format: string, value?: any) => {
  if (!editorRef.value) return

  editorRef.value.focus()

  switch (format) {
    case 'bold':
      document.execCommand('bold')
      break
    case 'italic':
      document.execCommand('italic')
      break
    case 'underline':
      document.execCommand('underline')
      break
    case 'strike':
      document.execCommand('strikeThrough')
      break
    case 'clean':
      document.execCommand('removeFormat')
      break
  }

  updateFormatStates()
}

// 格式化标题
const formatHeader = (level: number | false) => {
  if (!quillInstance) return

  const range = quillInstance.getSelection()
  if (!range) return

  quillInstance.format('header', level)
}

// 改变文本颜色
const changeTextColor = (color: string) => {
  if (!quillInstance) return

  const range = quillInstance.getSelection()
  if (!range) return

  quillInstance.format('color', color)
}

// 改变背景颜色
const changeBackgroundColor = (color: string) => {
  if (!quillInstance) return

  const range = quillInstance.getSelection()
  if (!range) return

  quillInstance.format('background', color)
}

// 撤销
const undo = () => {
  if (!quillInstance) return
  quillInstance.history.undo()
}

// 重做
const redo = () => {
  if (!quillInstance) return
  quillInstance.history.redo()
}

// 插入链接
const insertLink = () => {
  if (!quillInstance) return

  const range = quillInstance.getSelection()
  if (!range) return

  const text = quillInstance.getText(range.index, range.length)
  linkForm.text = text || ''
  linkForm.url = ''
  linkForm.target = '_self'
  linkDialogVisible.value = true
}

// 确认插入链接
const confirmInsertLink = () => {
  if (!quillInstance || !linkForm.url) return

  const range = quillInstance.getSelection()
  if (!range) return

  if (linkForm.text) {
    quillInstance.deleteText(range.index, range.length)
    quillInstance.insertText(range.index, linkForm.text)
    quillInstance.setSelection(range.index, linkForm.text.length)
  }

  quillInstance.format('link', {
    href: linkForm.url,
    target: linkForm.target
  })

  linkDialogVisible.value = false
}

// 插入图片
const insertImage = () => {
  imageForm.url = ''
  imageForm.alt = ''
  imageForm.title = ''
  imageTabActive.value = 'upload'
  imageDialogVisible.value = true
}

// 图片上传前验证
const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  return true
}

// 图片上传成功
const handleImageUploadSuccess = (response: any) => {
  if (response.code === 0) {
    insertImageToEditor(response.data.url, '', '')
    imageDialogVisible.value = false
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.msg || '图片上传失败')
  }
}

// 图片上传失败
const handleImageUploadError = () => {
  ElMessage.error('图片上传失败')
}

// 确认插入图片
const confirmInsertImage = () => {
  if (!imageForm.url) {
    ElMessage.warning('请输入图片地址')
    return
  }

  insertImageToEditor(imageForm.url, imageForm.alt, imageForm.title)
  imageDialogVisible.value = false
}

// 插入图片到编辑器
const insertImageToEditor = (url: string, alt: string, title: string) => {
  if (!quillInstance) return

  const range = quillInstance.getSelection()
  if (!range) return

  quillInstance.insertEmbed(range.index, 'image', {
    src: url,
    alt: alt,
    title: title
  })
}

// 插入视频
const insertVideo = () => {
  ElMessageBox.prompt('请输入视频地址', '插入视频', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^https?:\/\/.+/,
    inputErrorMessage: '请输入有效的视频地址'
  }).then(({ value }) => {
    if (!quillInstance) return

    const range = quillInstance.getSelection()
    if (!range) return

    quillInstance.insertEmbed(range.index, 'video', value)
  }).catch(() => {
    // 用户取消
  })
}

// 插入表格
const insertTable = () => {
  tableForm.rows = 3
  tableForm.cols = 3
  tableForm.style = 'default'
  tableDialogVisible.value = true
}

// 确认插入表格
const confirmInsertTable = () => {
  if (!quillInstance) return

  const range = quillInstance.getSelection()
  if (!range) return

  const tableModule = quillInstance.getModule('better-table')
  tableModule.insertTable(tableForm.rows, tableForm.cols)

  tableDialogVisible.value = false
}

// 插入代码块
const insertCodeBlock = () => {
  codeForm.language = 'javascript'
  codeForm.code = ''
  codeDialogVisible.value = true
}

// 确认插入代码
const confirmInsertCode = () => {
  if (!quillInstance || !codeForm.code) return

  const range = quillInstance.getSelection()
  if (!range) return

  quillInstance.insertText(range.index, '\n')
  quillInstance.insertEmbed(range.index + 1, 'code-block', {
    language: codeForm.language,
    code: codeForm.code
  })

  codeDialogVisible.value = false
}

// 插入数学公式
const insertFormula = () => {
  formulaForm.type = 'inline'
  formulaForm.latex = ''
  formulaDialogVisible.value = true
}

// 更新公式预览
const updateFormulaPreview = () => {
  if (!formulaPreviewRef.value || !formulaForm.latex) return

  try {
    katex.render(formulaForm.latex, formulaPreviewRef.value, {
      displayMode: formulaForm.type === 'block'
    })
  } catch (error) {
    formulaPreviewRef.value.innerHTML = '<span style="color: red;">公式语法错误</span>'
  }
}

// 确认插入公式
const confirmInsertFormula = () => {
  if (!quillInstance || !formulaForm.latex) return

  const range = quillInstance.getSelection()
  if (!range) return

  quillInstance.insertEmbed(range.index, 'formula', formulaForm.latex)
  formulaDialogVisible.value = false
}

// 插入分割线
const insertDivider = () => {
  if (!quillInstance) return

  const range = quillInstance.getSelection()
  if (!range) return

  quillInstance.insertText(range.index, '\n')
  quillInstance.insertEmbed(range.index + 1, 'divider', true)
  quillInstance.insertText(range.index + 2, '\n')
}

// 切换全屏
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value

  if (isFullscreen.value) {
    document.body.style.overflow = 'hidden'
  } else {
    document.body.style.overflow = ''
  }
}

// 切换预览
const togglePreview = () => {
  showPreview.value = !showPreview.value
}

// 获取内容
const getContent = () => {
  return quillInstance?.root.innerHTML || ''
}

// 设置内容
const setContent = (content: string) => {
  if (!quillInstance) return
  quillInstance.root.innerHTML = content
}

// 获取纯文本
const getText = () => {
  return quillInstance?.getText() || ''
}

// 清空内容
const clear = () => {
  if (!quillInstance) return
  quillInstance.setText('')
}

// 聚焦编辑器
const focus = () => {
  if (!quillInstance) return
  quillInstance.focus()
}

// 失焦编辑器
const blur = () => {
  if (!quillInstance) return
  quillInstance.blur()
}

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  if (!quillInstance) return

  const currentContent = quillInstance.root.innerHTML
  if (newValue !== currentContent) {
    quillInstance.root.innerHTML = newValue || ''
  }
})

// 生命周期
onMounted(() => {
  nextTick(() => {
    initEditor()
  })
})

onBeforeUnmount(() => {
  if (isFullscreen.value) {
    document.body.style.overflow = ''
  }

  if (quillInstance) {
    quillInstance = null
  }
})

// 暴露方法给父组件
defineExpose({
  getContent,
  setContent,
  getText,
  clear,
  focus,
  blur,
  undo,
  redo,
  insertImage: insertImageToEditor,
  insertLink: confirmInsertLink,
  insertTable: confirmInsertTable,
  insertCode: confirmInsertCode,
  insertFormula: confirmInsertFormula
})
</script>

<style lang="scss" scoped>
.rich-text-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;

  &.fullscreen {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    background: #fff;
  }

  .editor-toolbar {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
    padding: 12px;
    border-bottom: 1px solid #e4e7ed;
    background: #f8f9fa;

    .toolbar-group {
      display: flex;
      align-items: center;
      gap: 4px;

      .el-button {
        &.active {
          background: #409eff;
          color: #fff;
          border-color: #409eff;
        }
      }
    }
  }

  .editor-container {
    position: relative;
    display: flex;

    &.fullscreen {
      height: calc(100vh - 120px);
    }

    &.readonly {
      .editor-content {
        background: #f5f7fa;
      }
    }

    .editor-content {
      flex: 1;
      min-height: 400px;

      :deep(.ql-editor) {
        min-height: 400px;
        font-size: 14px;
        line-height: 1.6;

        &.ql-blank::before {
          font-style: normal;
          color: #c0c4cc;
        }

        // 代码块样式
        .ql-code-block-container {
          background: #f6f8fa;
          border: 1px solid #e1e4e8;
          border-radius: 6px;
          margin: 16px 0;

          .ql-code-block {
            background: transparent;
            border: none;
            color: #24292e;
            font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
            font-size: 12px;
            padding: 16px;
          }
        }

        // 表格样式
        table {
          border-collapse: collapse;
          margin: 16px 0;
          width: 100%;

          td, th {
            border: 1px solid #dfe2e5;
            padding: 8px 12px;
            text-align: left;
          }

          th {
            background: #f6f8fa;
            font-weight: 600;
          }

          &.bordered {
            border: 2px solid #dfe2e5;
          }

          &.striped {
            tr:nth-child(even) {
              background: #f6f8fa;
            }
          }
        }

        // 公式样式
        .ql-formula {
          margin: 8px 0;

          &.ql-formula-block {
            display: block;
            text-align: center;
            margin: 16px 0;
          }
        }

        // 图片样式
        img {
          max-width: 100%;
          height: auto;
          border-radius: 4px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        // 视频样式
        video {
          max-width: 100%;
          height: auto;
          border-radius: 4px;
        }

        // 分割线样式
        hr {
          border: none;
          border-top: 2px solid #e1e4e8;
          margin: 24px 0;
        }

        // 引用样式
        blockquote {
          border-left: 4px solid #dfe2e5;
          margin: 16px 0;
          padding: 0 16px;
          color: #6a737d;
        }

        // 列表样式
        ul, ol {
          padding-left: 24px;

          li {
            margin: 4px 0;
          }
        }
      }
    }

    .editor-preview {
      flex: 1;
      border-left: 1px solid #e4e7ed;
      background: #fff;
      overflow-y: auto;

      .preview-content {
        padding: 20px;
        font-size: 14px;
        line-height: 1.6;
        color: #303133;
      }
    }
  }

  .editor-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    border-top: 1px solid #e4e7ed;
    background: #f8f9fa;
    font-size: 12px;
    color: #909399;

    .word-count {
      display: flex;
      gap: 16px;
    }
  }
}

// 对话框样式
.image-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
    }
  }

  :deep(.el-upload-dragger) {
    background-color: #fff;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    box-sizing: border-box;
    width: 100%;
    height: 180px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
    }

    .el-icon--upload {
      font-size: 67px;
      color: #c0c4cc;
      margin: 40px 0 16px;
      line-height: 50px;
    }

    .el-upload__text {
      color: #606266;
      font-size: 14px;
      text-align: center;

      em {
        color: #409eff;
        font-style: normal;
      }
    }
  }
}

.formula-preview {
  min-height: 60px;
  padding: 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #f8f9fa;
  text-align: center;

  &:empty::before {
    content: '公式预览将在这里显示';
    color: #c0c4cc;
    font-style: italic;
  }
}

// 全屏模式样式
.fullscreen {
  .editor-container {
    height: calc(100vh - 140px) !important;

    .editor-content {
      min-height: auto !important;

      :deep(.ql-editor) {
        min-height: auto !important;
        height: 100%;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .rich-text-editor {
    .editor-toolbar {
      padding: 8px;
      gap: 4px;

      .toolbar-group {
        gap: 2px;
      }

      .el-button {
        padding: 4px 8px;
        font-size: 12px;
      }

      .el-select {
        width: 100px !important;
      }
    }

    .editor-container {
      flex-direction: column;

      .editor-preview {
        border-left: none;
        border-top: 1px solid #e4e7ed;
        max-height: 300px;
      }
    }
  }
}

// 暗色主题支持
@media (prefers-color-scheme: dark) {
  .rich-text-editor {
    border-color: #4c4d4f;
    background: #1d1e1f;

    .editor-toolbar {
      background: #2d2e2f;
      border-color: #4c4d4f;
    }

    .editor-container {
      .editor-content {
        background: #1d1e1f;

        :deep(.ql-editor) {
          color: #e4e6ea;

          &.ql-blank::before {
            color: #8a8b8c;
          }
        }
      }

      .editor-preview {
        background: #1d1e1f;
        border-color: #4c4d4f;

        .preview-content {
          color: #e4e6ea;
        }
      }
    }

    .editor-footer {
      background: #2d2e2f;
      border-color: #4c4d4f;
      color: #8a8b8c;
    }
  }
}
</style>
